package main.proyecto_pei;


import utilities.BDSQLiteHelper;
import utilities.Preferencias;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class Configuracion extends AcercaDe{
	
	TextView txtMensaje;
	CheckBox checkVibrar,checkSonido,checkNotifLlamada,checkNotifSms;
	public static CheckBox checkNotifLimPresup;
	RadioButton rbDefaul,rbExtremeAlarm,rbIphoneAlarm,rbNuclearAlarm,rbSuperAlarm,rbSweetAlarm,rbZelda;
	Integer sonido=null;
	MediaPlayer player;
	Preferencias pref;
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	    super.onConfigurationChanged(newConfig);
	}
	
	@Override
	public void onCreate(Bundle SavedInstanceState){
		super.onCreate(SavedInstanceState);
		setContentView(R.layout.configuracion);
		txtMensaje = (TextView)findViewById(R.id.txtMensajeAlerta);
		checkVibrar = (CheckBox)findViewById(R.id.checkVibrar);
		checkSonido = (CheckBox)findViewById(R.id.checkSonido);
		checkNotifLlamada = (CheckBox)findViewById(R.id.checkNotificarLlamada);
		checkNotifSms = (CheckBox)findViewById(R.id.checkNotificarSms);
		checkNotifLimPresup = (CheckBox)findViewById(R.id.checkNotificarLimPresupuesto);
		pref = new Preferencias(Configuracion.this);
		
		if(pref.getPref(Preferencias.NOTIFICAR_TERMINA_LLAMADA, Preferencias.NO).equals(Preferencias.SI))checkNotifLlamada.setChecked(true);
		if(pref.getPref(Preferencias.NOTIFICAR_ENVIAR_SMS, Preferencias.NO).equals(Preferencias.SI))checkNotifSms.setChecked(true);
		if(pref.getPref(Preferencias.NOTIFICAR_LIM_PRESUP, Preferencias.NO).equals(Preferencias.SI))checkNotifLimPresup.setChecked(true);
		
		checkSonido.setOnCheckedChangeListener(new OnCheckedChangeListener(){
		    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
		    	if(isChecked)
		    		showDialog(0);
		    }
		});
		
		checkNotifLlamada.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked) pref.setPref(Preferencias.NOTIFICAR_TERMINA_LLAMADA, Preferencias.SI);
				else pref.setPref(Preferencias.NOTIFICAR_TERMINA_LLAMADA, Preferencias.NO);
		}});
		checkNotifSms.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked) pref.setPref(Preferencias.NOTIFICAR_ENVIAR_SMS, Preferencias.SI);
				else pref.setPref(Preferencias.NOTIFICAR_ENVIAR_SMS, Preferencias.NO);
		}});
		checkNotifLimPresup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked) pref.setPref(Preferencias.NOTIFICAR_LIM_PRESUP, Preferencias.SI);
				else pref.setPref(Preferencias.NOTIFICAR_LIM_PRESUP, Preferencias.NO);
		}});
		checkNotifLimPresup.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if(!checkNotifLimPresup.isEnabled())
					Toast.makeText(Configuracion.this, "No se ha creado un presupuesto", Toast.LENGTH_SHORT).show();
				return false;
			}
		});
		
		if(pref.getPref(Preferencias.EXISTE_PRESUPUESTO, Preferencias.NO).equals(Preferencias.NO)){
			checkNotifLimPresup.setEnabled(false);
		}
		
	}
		
	/********************************************************************/
	/**						FUNCIONES DE BOTONES						*/
	/********************************************************************/
	
	public void onClickVerALertas(View v){
		Intent i = new Intent(Configuracion.this, VerAlertas.class );
        startActivity(i);
	}

	public void onClickGuardar(View v){
		if(txtMensaje.getText().toString().trim().equals(""))
			Toast.makeText(this, "Ingrese el mensaje", Toast.LENGTH_SHORT).show();
		else{
			guardarAlarma();
		}
	}
	
	/********************************************************************/
	/**						FUNCIONES VARIAS							*/
	/********************************************************************/
	
	private void guardarAlarma() {
		BDSQLiteHelper usdbh = new BDSQLiteHelper(this, "DB_PEI", null, 1);
		SQLiteDatabase db = null;
		int vib=0;
		if(checkVibrar.isChecked()) vib =1;
		try {
			db = usdbh.getReadableDatabase();
			Cursor c = db.query("PEI_PLAN", new String[] {"ID_PLAN"}, null, null, null, null, null);
			if(c.moveToFirst()){//Si existe un plan guardamos la alarma, sino no
				db.execSQL("INSERT INTO PEI_ALERTA(MENSAJE,IS_ACTIVO,SONIDO,VIBRAR) VALUES(" +
						"'"+txtMensaje.getText().toString().trim()+"'," +
								"'0',"+//Al momento de la creacion IS_ACTIVO por defecto sera false
								"'"+sonido+"'," +
								"'"+vib+"')");
				Toast.makeText(this, "Alerta Guardada", Toast.LENGTH_SHORT).show();
				txtMensaje.setText("");
				checkSonido.setChecked(false);
				checkVibrar.setChecked(false);
			}
			else{
				Toast.makeText(this,"Debe crear el plan para agregar alarmas" , Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.i("ERROR GAURDARALERTA", e.getMessage());
		}
		finally{
			db.close();
		}
	}
	


	/********************************************************************/
	/**								DIALOGOS							*/
	/********************************************************************/
	@Override
	protected Dialog onCreateDialog(int id) {
	 Dialog dialog = null;
	    switch(id) {
    	    case 0:
    	    	dialog = new Dialog(Configuracion.this);
	    	    dialog.setContentView(R.layout.itemsonido);
	    	    rbDefaul =  (RadioButton)dialog.findViewById(R.id.rbtnSonidoDefault);
	    		rbExtremeAlarm = (RadioButton)dialog.findViewById(R.id.rbtnSonidoExtremeClock);
	    		rbIphoneAlarm = (RadioButton)dialog.findViewById(R.id.rbtnSonidoIphoneAlarm);
	    		rbNuclearAlarm = (RadioButton)dialog.findViewById(R.id.rbtnSonidoNuclearAlarm);
	    		rbSuperAlarm = (RadioButton)dialog.findViewById(R.id.rbtnSonidoSuperAlarm);
	    		rbSweetAlarm = (RadioButton)dialog.findViewById(R.id.rbtnSonidoSweetWake);
	    		rbZelda = (RadioButton)dialog.findViewById(R.id.rbtnSonidoZelda);
	    		cambiarChangeListener(cambioSonido);
	    		rbDefaul.setChecked(true);
	    		Button btnCancelar = (Button)dialog.findViewById(R.id.btnCancelarSonido);
	    	    Button btnAceptar = (Button)dialog.findViewById(R.id.btnAceptarSonido);
	    	    btnCancelar.setOnClickListener(onClickCancelar);
	    	    btnAceptar.setOnClickListener(onClickAceptar);
	    	    dialog.setTitle("Sonidos");
	    }
	    return dialog;
	}
	private OnClickListener onClickCancelar = new OnClickListener() {
        public void onClick(View v) {
            checkSonido.setChecked(false);
            sonido=null;
            if(player!=null) player.stop();
            dismissDialog(0);
        }
    };
    private OnClickListener onClickAceptar = new OnClickListener() {
        public void onClick(View v) {
            if(rbExtremeAlarm.isChecked()) sonido = R.raw.extreme_clock_alarm;
            else if(rbIphoneAlarm.isChecked()) sonido = R.raw.iphone_alarm;
            else if(rbNuclearAlarm.isChecked()) sonido = R.raw.nuclear_alarm;
            else if(rbSuperAlarm.isChecked()) sonido = R.raw.super_alarm;
            else if(rbSweetAlarm.isChecked()) sonido = R.raw.sweet_wake_up;
            else if(rbZelda.isChecked()) sonido = R.raw.zelda;
            else sonido=-1;//Default
            if(player!=null) player.stop();
            dismissDialog(0);
        }
    };
	private OnCheckedChangeListener cambioSonido = new OnCheckedChangeListener(){
	    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
	    	RadioButton rb = (RadioButton)buttonView;
	    	//Desactivamos el listener para que al ponerlos todos a falso no se dispare
	    	cambiarChangeListener(null);
	    	rbDefaul.setChecked(false);
	    	rbExtremeAlarm.setChecked(false);
	    	rbIphoneAlarm.setChecked(false);
	    	rbNuclearAlarm.setChecked(false);
	    	rbSuperAlarm.setChecked(false);
	    	rbSweetAlarm.setChecked(false);
	    	rbZelda.setChecked(false);
	    	if(player!=null) player.stop();
	    	if(rb.getText().equals(getString(R.string.lblSonidoDefault))){
	    		rbDefaul.setChecked(true);
	    		try{
		    		Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		    		Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
		    		r.play();
	    		}catch(Exception e){e.printStackTrace();}
	    	}
	    	else if(rb.getText().equals(getString(R.string.lblSonidoExtremeAlarm))){
	    		rbExtremeAlarm.setChecked(true);
	    		launchAlarm(R.raw.extreme_clock_alarm);
	    	}
	    	else if(rb.getText().equals(getString(R.string.lblSonidoIhponeAlarm))){
	    		rbIphoneAlarm.setChecked(true);
	    		launchAlarm(R.raw.iphone_alarm);
	    	}
			else if(rb.getText().equals(getString(R.string.lblSonidoNuclearAlarm))){
				rbNuclearAlarm.setChecked(true);
				launchAlarm(R.raw.nuclear_alarm);
			}
			else if(rb.getText().equals(getString(R.string.lblSonidoSuperAlarm))){
				rbSuperAlarm.setChecked(true);
				launchAlarm(R.raw.super_alarm);
			}
			else if(rb.getText().equals(getString(R.string.lblSonidoSweetWakeup))){
				rbSweetAlarm.setChecked(true);
				launchAlarm(R.raw.sweet_wake_up);
			}
			else if(rb.getText().equals(getString(R.string.lblSonidoZelda))){
				rbZelda.setChecked(true);
				launchAlarm(R.raw.zelda);
			}
	    	cambiarChangeListener(cambioSonido);
	    }
	};
	
	private void cambiarChangeListener(OnCheckedChangeListener cl){
		rbDefaul.setOnCheckedChangeListener(cl);
		rbExtremeAlarm.setOnCheckedChangeListener(cl);
		rbIphoneAlarm.setOnCheckedChangeListener(cl);
		rbNuclearAlarm.setOnCheckedChangeListener(cl);
		rbSuperAlarm.setOnCheckedChangeListener(cl);
		rbSweetAlarm.setOnCheckedChangeListener(cl);
		rbZelda.setOnCheckedChangeListener(cl);
	}
	
	private void launchAlarm(Integer s){
		player = MediaPlayer.create(this, s);
		
		player.setLooping(false); // Set looping
		player.start();
	}

}
